<?php

/**
 * This is the model class for table "{{goods}}".
 *  比商品报名表少了的字段  
 *  City CreditScore Location Province UserID UserName AdminID Money MoneyBond ServiceFee IsPay
 *  商吕表比报名表 少了若干个不紧要的字段
 * The followings are the available columns in table '{{goods}}':
 * @property string $GoodsID
 * @property string $GoodsBmID
 * @property string $DetailUrl
 * @property string $Image
 * @property integer $ItemType
 * @property string $Nick
 * @property string $Pprice
 * @property string $ProductID
 * @property string $PromoPrice
 * @property string $Sales
 * @property string $Sorting
 * @property string $CatID
 * @property string $ModuleID
 * @property string $StartTime
 * @property string $EndTime
 * @property string $SpecialID
 * @property string $PlanSale
 * @property integer $IsGather
 * @property string $TaobaoUrl
 */
class GoodsModel extends BaseModel
{
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{goods}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('GoodsName,DetailUrl, Image, CatID', 'required'),
			array('PlanSale', 'required','on'=>'front'),
			array('TaobaoUrl', 'match','pattern'=>'/^http:\/\//','on'=>'admin'),
			array('TaobaoUrl', 'checkQuite','on'=>'admin'),
			array('PlanSale, CatID,StartSales,AdminID,IsIndex', 'numerical', 'integerOnly'=>true),
			array('Brief,View,Zhekou', 'safe'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('GoodsBmID, DetailUrl, Image, ItemType, Nick, Pprice, ProductID, PromoPrice, Sales, Sorting, CatID, ModuleID, StartTime, EndTime, SpecialID, PlanSale, IsGather, TaobaoUrl,AdminID,StartSales,IsIndex,UpdateTime,IsPreferential,IsHot,IsNew,CountSales,CountStartSales,Status,IsFreeShipping,AddTime', 'safe', 'on'=>'admin'),
			array('GoodsID, GoodsBmID, DetailUrl, Image, ItemType, Nick, Pprice, ProductID, PromoPrice, Sales, Sorting, CatID, ModuleID, StartTime, EndTime, SpecialID, PlanSale, IsGather, TaobaoUrl,IsIndex,UpdateTime,Status,IsFreeShipping', 'safe', 'on'=>'search'),
		);
	}

	public function checkQuite(){
		if($this->isNewRecord){
			if($model = self::model()->find(BaseModel::getC(array('ProductID' => $this->ProductID, 'order' => 'GAddTime DESC')))){
				if($model->EndTime > TIME_TIME && $model->Status == 1){
					$this->addError('', '系统已经存在此商品,还未下架');
				}
			}
		}
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			//self::HAS_MANY  我的这个表的主键去关联TagGoodsModel这个表的GoodsID这个字段  
			//self::BELONGS_TO  我的这个表的GoodsName 去关联 TagGoodsModel这个表的主键
			//self::HAS_ONE 我的这个表的主键去关联TagGoodsModel的GoodssID
			'TagGoodsModel' => array(self::HAS_MANY, 'TagGoodsModel', 'GoodsID'),
			'ModuleGoodsModel' => array(self::HAS_MANY, 'ModuleGoodsModel', 'GoodsID'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'GoodsID' => '商品主键ID',
			'GAddTime' => '添加时间',
			'GoodsName' => '商品名',
			'GoodsBmID' => '报名ID',
			'DetailUrl' => '链接地址',
			'Image' => '图片',
			'ItemType' => '店铺类型',
			'Nick' => '商家旺旺',
			'Pprice' => '原价',
			'ProductID' => '商品ID',
			'PromoPrice' => '折扣价',
			'Sales' => '销量',
			'Sorting' => '排序',
			'CatID' => '分类ID',
			'ModuleID' => '模块ID',
			'StartTime' => '开始时间',
			'EndTime' => '结束时间',
			'SpecialID' => '专场ID',
			'PlanSale' => '计划销量',
			'IsGather' => '是否采集',
			'TaobaoUrl' => '淘宝URL',
			'IsIndex' => '首页轮播',
			'UpdateTime' => '修改时间',//状态修改时间，比如什么时候上架，下架等这状态
			'Tag' => '标签',//状态修改时间，比如什么时候上架，下架等这状态
			'IsPreferential' => '特惠商品',
			'IsHot' => '热门商品',
			'IsNew' => '最新商品',
			'CountStartSales' => '自己统计的初始销量',
			'CountSales' => '目前自己统计的销量',
			'IsFreeShipping' => '是否免运费',
			'Brief' => '简介',
			'Module' => '版块/模块',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('GoodsID',$this->GoodsID,true);
		$criteria->compare('GoodsBmID',$this->GoodsBmID,true);
		$criteria->compare('GoodsName',$this->GoodsName,true);
		$criteria->compare('DetailUrl',$this->DetailUrl,true);
		$criteria->compare('Image',$this->Image,true);
		$criteria->compare('ItemType',$this->ItemType);
		$criteria->compare('Nick',$this->Nick,true);
		$criteria->compare('Pprice',$this->Pprice,true);
		if($this->ProductID > 0){
			$criteria->compare('ProductID',$this->ProductID);
		}
		$criteria->compare('PromoPrice',$this->PromoPrice,true);
		$criteria->compare('Sales',$this->Sales,true);
		$criteria->compare('Sorting',$this->Sorting,true);
		$criteria->compare('CatID',$this->CatID,true);
		$criteria->compare('ModuleID',$this->ModuleID,true);
		$criteria->compare('StartTime',$this->StartTime,true);
		$criteria->compare('EndTime',$this->EndTime,true);
		$criteria->compare('SpecialID',$this->SpecialID,true);
		$criteria->compare('PlanSale',$this->PlanSale,true);
		$criteria->compare('IsGather',$this->IsGather);
		$criteria->compare('TaobaoUrl',$this->TaobaoUrl,true);
		$criteria->compare('IsIndex',$this->IsIndex);
		$criteria->compare('IsPreferential',$this->IsPreferential);
		$criteria->compare('IsHot',$this->IsHot);
		$criteria->compare('IsNew',$this->IsNew);
		$criteria->compare('Status',$this->Status);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	public function createSearchCriteria(){
		$criteria=new CDbCriteria;

		$criteria->compare('GoodsID',$this->GoodsID,true);
		$criteria->compare('GoodsBmID',$this->GoodsBmID,true);
		$criteria->compare('GoodsName',$this->GoodsName,true);
		$criteria->compare('DetailUrl',$this->DetailUrl,true);
		$criteria->compare('Image',$this->Image,true);
		$criteria->compare('ItemType',$this->ItemType);
		$criteria->compare('Nick',$this->Nick,true);
		$criteria->compare('Pprice',$this->Pprice,true);
		if($this->ProductID > 0){
			$criteria->compare('ProductID',$this->ProductID);
		}
		$criteria->compare('PromoPrice',$this->PromoPrice,true);
		$criteria->compare('Sales',$this->Sales,true);
		$criteria->compare('Sorting',$this->Sorting,true);
		$criteria->compare('SpecialID',$this->SpecialID,true);
		$criteria->compare('PlanSale',$this->PlanSale,true);
		$criteria->compare('IsGather',$this->IsGather);
		$criteria->compare('TaobaoUrl',$this->TaobaoUrl,true);
		$criteria->compare('IsIndex',$this->IsIndex);
		$criteria->compare('IsPreferential',$this->IsPreferential);
		$criteria->compare('IsHot',$this->IsHot);
		$criteria->compare('IsNew',$this->IsNew);
		$criteria->compare('Status',$this->Status);



		if(!empty($this->CatID)){
			$catids = CategoryModel::getStrChildid($this->CatID);
			//echo $catids;exit;
			$criteria->addCondition("CatID in ($catids)");	
		}



		if(is_numeric($this->StartTime)){
			$criteria->compare('StartTime',$this->StartTime,true);
		}else{
			if(!empty($this->StartTime)){
				$StartTime = strtotime($this->StartTime);
				$criteria->addCondition('StartTime >= ' . $StartTime);	
			}		
		}

		if(is_numeric($this->EndTime)){
			$criteria->compare('EndTime',$this->EndTime,true);
		}else{
			if(!empty($this->EndTime)){
				$EndTime = strtotime($this->EndTime) + 86400;
				$criteria->addCondition('StartTime < ' . $EndTime);
			}			
		}
		
		return 	$criteria;	
	}


	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return GoodsModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}


	public function beforeSave(){

		if(GROUP_NAME !== 'admin'){
			return true;
		}		
		
		if(CONTROLLER_NAME == 'sales'){
			return true;
		}
		if(ACTION_NAME == 'updateOne'){
			if(!is_numeric($this->StartTime)){
				$this->StartTime = strtotime($this->StartTime);
			}

			if(!is_numeric($this->EndTime)){
				$this->EndTime = strtotime($this->EndTime);
			}
		}else{
			if(!is_numeric($this->StartTime)){
				$this->StartTime = strtotime(date('Y-m-d 9:00:00', strtotime($this->StartTime)));
			}

			if(!is_numeric($this->EndTime)){
				$this->EndTime = strtotime(date('Y-m-d 9:00:00', strtotime($this->EndTime)));
			}			
		}


		$objModel = self::model()->findByPk($this->GoodsID);
		if($this->Status != $objModel->Status){			
			$this->UpdateTime = TIME_TIME;	
		}


		//如果是新增的表示是自己采集的商品
		//City CreditScore Location Province UserID UserName AdminID Money MoneyBond ServiceFee IsPay
		if($this->isNewRecord){
			$this->Zhekou = $this->Pprice/$this->PromoPrice;
			$this->GAddTime = TIME_TIME;
			$this->UpdateTime = TIME_TIME;			
			//刚开始的时候初始销量等于获取的销量
		}else{
			//把修改的东西同步到商品表
			if($model = GoodsBmModel::model()->findByPk($this->GoodsBmID)){
				if($model->Status != $this->Status){
					$this->UpdateTime = TIME_TIME;
				}
				$model->setScenario('admin');          
				$model->attributes = $this->attributes;
				$model->save(false);
			}
			$oldModel = self::model()->findByPk($this->GoodsID);
			if($oldModel->Status != $this->Status){
				//如果状态已经跟原来不一样
				if($this->Status != 1){
					//已经下架了或其它的一些情况,这样的情况把关联这商品的 模块商品表  与  标签商品表的 数据删除
					TagGoodsModel::model()->deleteAll(BaseModel::getC(array('GoodsID' => $this->GoodsID)));
					ModuleGoodsModel::model()->deleteAll(BaseModel::getC(array('GoodsID' => $this->GoodsID)));
				}
			}
		}
		return true;
	}
	//getOne有的是所有的都可能会出现，包括下架的等
	//getList 只取正在上架中，所以当变化的时候需要更换两个。。。。。
	public function afterDelete(){
		self::getOne($this->GoodsID, false);
		self::getList(false);
	}

	public function afterSave(){


		if(GROUP_NAME !== 'admin'){
			return true;
		}


		if(CONTROLLER_NAME == 'sales'){
			return true;
		}
		//添加成功然后就看一下是否是需要添加这标签商品
		//自己添加的标签。
		if(!empty($_POST['GoodsModel']['Tag'])){
			//先找出原先已经存在的，然后再对比看是否需要删除，
			$arrTag = $this->getTag();//现此商品存在的taggoods
			$arrD = array();
			foreach ($_POST['GoodsModel']['Tag'] as $TagID) {
				if(in_array($TagID, $arrTag)){
					//这些是已经有了的，不需要删除
					$arrD[] = $TagID;
				}else{
					TagGoodsModel::saveData($TagID, $this->GoodsID);
				}								
			}
			//现在则是需要删除的
			$arr = array();
			foreach ($arrTag as $TagID) {
				if(!in_array($TagID, $arrD)){
					$arr[] = $TagID;
				}
			}

			if($arr){
				TagGoodsModel::model()->deleteAll(BaseModel::getC(array('GoodsID' => $this->GoodsID, 'TagID' => array('sign' => 'in', 'data' => BaseModel::getStrIn($arr)))));
				TagGoodsModel::getList($this->GoodsID, false);
			}
		}else{
			if(IS_POST){
				$arr = $this->getTag();//现此商品存在的taggoods	
				if($arr){
					TagGoodsModel::model()->deleteAll(BaseModel::getC(array('GoodsID' => $this->GoodsID, 'TagID' => array('sign' => 'in', 'data' => BaseModel::getStrIn($arr)))));
					TagGoodsModel::getList($this->GoodsID, false);
				}	
			}				
		}

		//添加成功然后就看一下是否是需要添加这标签商品
		if(!empty($_POST['GoodsModel']['Tag_add'])){
			//先找出原先已经存在的，然后再对比看是否需要删除，
			//$arrTag = $this->getTag();
			foreach ($_POST['GoodsModel']['Tag_add'] as $key => $strTagNmae) {
				//先看一下是否有这个名称的标签，如果没有的话则新增
				TagGoodsModel::saveDataTag($strTagNmae, $this->GoodsID);				
			}
		}




		//添加成功然后就看一下是否是需要添加这标签商品
		//自己添加的标签。
		if(!empty($_POST['GoodsModel']['Module'])){
			//先找出原先已经存在的，然后再对比看是否需要删除，
			$arrTag = $this->getModule();//现此商品存在的taggoods
			$arrD = array();
			foreach ($_POST['GoodsModel']['Module'] as $ModuleID) {
				if(in_array($ModuleID, $arrTag)){
					//这些是已经有了的，不需要删除
					$arrD[] = $ModuleID;
				}else{
					ModuleGoodsModel::saveData($ModuleID, $this->GoodsID);
				}								
			}
			//现在则是需要删除的
			$arr = array();
			foreach ($arrTag as $ModuleID) {
				if(!in_array($ModuleID, $arrD)){
					$arr[] = $ModuleID;
				}
			}

			if($arr){
				ModuleGoodsModel::model()->deleteAll(BaseModel::getC(array('GoodsID' => $this->GoodsID, 'ModuleID' => array('sign' => 'in', 'data' => BaseModel::getStrIn($arr)))));
				ModuleGoodsModel::getList($this->GoodsID, false);
			}
		}else{
			if(IS_POST){
				$arr = $this->getModule();//现此商品存在的taggoods	
				if($arr){
					ModuleGoodsModel::model()->deleteAll(BaseModel::getC(array('GoodsID' => $this->GoodsID, 'ModuleID' => array('sign' => 'in', 'data' => BaseModel::getStrIn($arr)))));
					ModuleGoodsModel::getList($this->GoodsID, false);
				}	
			}				
		}


		self::getOne($this->GoodsID, false);
		self::getList(false);

	}


	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getItemTypeHtml($mixData = false){
		$arrData = array(
			0 => '淘宝',
			1 => '天猫',
			2 => '天猫精品',			
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}

    /**
     * 取消活动（利用用户取消报名实现）
     * @param type $object 商品ID或者商品对象
     * @return boolean
     */
    public function activity() {
        if (empty($this->GoodsBmID)) {
            yii::app()->user->setFlash('找不到报名记录ID');
            return false;
        }
        $objGoodsBmModel = GoodsBmModel::model()->findByPk($this->GoodsBmID);
        if (empty($objGoodsBmModel)) {
        	yii::app()->user->setFlash('该商品的报名信息不存在，无法取消活动！');
            return false;
        }
        $this->Status = 4;
        $this->save(false);
        return true;
    }


    /**
     * 特殊的取商品方式
     */
    public static function getVariedGoodsMix($intModuleID, $intCatID, $intSpecialID,  $strTag, $intIsIndex, $IsFreeShipping, $extra, $strOrder, $intPage, $intPageSize,  $bloIsUpset, $bloIsCache, $intCacheTime){
        $strCache = "GoodsModel_getVariedGoods" . $intModuleID . '_' . $intCatID . '_' . $intSpecialID . '_' . $strTag . '_' . $intIsIndex . '_'  . $IsFreeShipping . '_'   . $extra . '_' . $strOrder . '_' . $intPage . '_' . $intPageSize;
        
        //如果这些条件的话则是另外的去获取商品

        $ConditionsExtra = (strpos($strTag, ',') !== false);//标签两个以上,不用缓存，其它的条件都用缓存

    	if($strOrder == 'onsale'){
    		return self::getVariedGoodsOnsale($intCatID, $intPage, $intPageSize, $bloIsUpset,$bloIsCache);
    	}

    	//通过缓存取所有的正在上架的商品列表
    	$arrResult = array();
    	$goods = self::getList();
    	$intCount = 0;
    	foreach ($goods as $GoodsID => $good) {
    		$intCount++;
    		//模块的条件
    		if($intModuleID){
    			//通过模块ID来取这模块ID下面的所有的商品
    			if(!in_array($GoodsID, ModuleGoodsModel::getListModuleField($intModuleID, 'GoodsID'))){
    				unset($goods[$GoodsID]);
    				$intCount--;
    				continue;
    			}
    		}
    		//分类的条件，
    		if($intCatID){
    			$a = CategoryModel::getArrChildid($intCatID);
    			//通过模块ID来取这模块ID下面的所有的商品
    			if(!in_array($good['CatID'], $a)){
    				unset($goods[$GoodsID]);
    				$intCount--;
    				continue;
    			}
    		}
    		//专场的条件，
    		if($intSpecialID){
    			//通过模块ID来取这模块ID下面的所有的商品
    			if($good['SpecialID'] != $intSpecialID){
    				unset($goods[$GoodsID]);
    				$intCount--;
    				continue;
    			}
    		}
    		//标签的条件
    		$arrTleshi = array();
    		$IS = false;
    		$arrTag = explode(',', $strTag);
    		foreach ($arrTag as $key => $tagID) {
    			//获取这个标签ID下面的所有的商品
    			$arr = TagGoodsModel::getListGoodsField($tagID, 'GoodsID');
    			if(in_array($GoodsID, $arr)){
    				$IS = true;
    				break;
    			}
    		}
    		if($IS === true){
    			unset($goods[$GoodsID]);
    			$intCount--;
    			continue;
    		}

    		//是否首页的，
    		if($intIsIndex){
    			//通过模块ID来取这模块ID下面的所有的商品
    			if($good['IsIndex'] != $intIsIndex){
    				unset($goods[$GoodsID]);
    				$intCount--;
    				continue;
    			}
    		}

    		//是否免运费
    		if($IsFreeShipping){
    			//通过模块ID来取这模块ID下面的所有的商品
    			if($good['IsFreeShipping'] != $IsFreeShipping){
    				unset($goods[$GoodsID]);
    				$intCount--;
    				continue;
    			}
    		}
    	}
    	//通过上面的循环，已经找到了所有符合条件的商品，接下来就是对其排序，分页，打乱顺序等操作。。。。。。。。。
    	//--------------------------------------------------------------------------------------------------------




    	//排序

    	$arrDatas = array();
    	$strOrder = str_replace(' ', '', $strOrder);//把所有的空格去掉
    	$arrOrder = explode(',', $strOrder);//把其变为数组  abcDESC  nnnASC 变成这种格式
    	$GLOBALS['arrT'] = array();
    	//获取要满足的所有条件，按顺序来
    	foreach($arrOrder as $str){
    		if(strpos(strtolower($str), 'desc')){
    			$GLOBALS['arrT'][] = array('field' => substr($str, 0, -4), 'order' => 'desc');
    		}else if(strpos(strtolower($str), 'asc')){
    			$GLOBALS['arrT'][] = array('field' => substr($str, 0, -3), 'order' => 'asc');
    		}
    	}


    	//对其进行排序。。//如果是正常的排序则是这样的操作
    	$arrOrder = array('default', 'zonghe', 'zhekou');
    	if(!in_array($strOrder, $arrOrder)){
			usort($goods, function($a, $b) {
				global $arrT;
				foreach($arrT as $arrF){
					$field = $arrF['field'];
					if($arrF['order'] == 'desc'){
						if($a[$field] > $b[$field]){
							return -1;
						}else if($a[$field] < $b[$field]){
							return 1;
						}else{
							continue;
						}
					}else{
						if($a[$field] > $b[$field]){
							return 1;
						}else if($a[$field] < $b[$field]){
							return -1;
						}else{
							continue;
						}							
					}
				}
			});    		
    	}else{
    		switch ($strOrder) {
    			case 'zonghe':
	    			//根据销量,价格，喜欢数，折扣，等来综合排名
					usort($goods, function($a, $b) {
						$a_count = 0;
						$b_count = 0;
						$a['Sales'] > $b['Sales'] ? $a_count++ : $b_count++;					
						$a['Pprice'] > $b['Pprice'] ? $a_count++ : $b_count++;
						$a['View'] > $b['View'] ? $a_count++ : $b_count++;
						($a['Pprice']/$a['PromoPrice']) > ($b['Pprice']/$b['PromoPrice']) ? $a_count++ : $b_count++;
						if($a_count > $b_count){
							return -1;
						}else{
							return 1;
						}
					});
    			break;
    			case 'zhekou':
					usort($goods, function($a, $b) {
						if(($a['Pprice']/$a['PromoPrice']) > ($b['Pprice']/$b['PromoPrice'])){
							return -1;
						}else{
							return 1;
						}
					});
    				break;
    			
    			default:
    				# code...
    				break;
    		}
    	}

        $arrResult['count'] = $intCount;
        $arrResult['data'] = $goods;

        $arrResult = self::getPageData($arrResult,$intPage, $intPageSize);



        //print_r(count($arrResult['data']));exit;
        //打乱顺序
        if($bloIsUpset === true){
            shuffle($arrResult['data']);
        }

        return $arrResult;

    }

    /**
     * 第一天60，第二天，30，其它百分10的算法，取这样的数据
     * @return [type] [description]
     */
    public static function getOnsaleData($intCatID){
    	//通过缓存取所有的正在上架的商品列表
    	$arrResult = array();
    	$goods = self::getList();
    	$intCount = 0;
    	foreach ($goods as $GoodsID => $good) {
    		$intCount++;
    		//分类的条件，
    		if($intCatID){
    			$a = CategoryModel::getArrChildid($intCatID);
    			//通过模块ID来取这模块ID下面的所有的商品
    			if(!in_array($good['CatID'], $a)){
    				unset($goods[$GoodsID]);
    				$intCount--;
    				continue;
    			}
    		}   		
    	}
    	$arrResult['count'] = $intCount;
    	//通过上面的循环，已经找到了所有符合条件的商品，接下来就是对其排序，分页，打乱顺序等操作。。。。。。。。。
    	//--------------------------------------------------------------------------------------------------------

    	//取出三天的数据
    	$arrRes = $arrToday = $arr1 = $arr2 = array();
    	foreach ($goods as $GoodsID => $good) {
    		//今天上架
    		if($good['StartTime'] > strtotime('today')){ //今天上架
    			$arrToday[$GoodsID] = $good;
    		}else if($good['StartTime'] > strtotime('-1 day')){//昨天上架
    			$arr1[$GoodsID] = $good;
    		}else{//其它时间上架
    			$arr2[$GoodsID] = $good;
    		}
    	}
    	//然后对其进行规则排序
    	for($i = 0;$i<$intCount;$i++){
    		//取1-100的随机数，如果是1-60则是当天的中了，如果是61-90，则是昨天的中了，91-100则其它的中了，如果没有了则往下推找，或者是往上推找
    		$rand = rand(1,100);
    		if($rand >= 1 && $rand <= 60){          //抽到1-60
    			if(!empty($arrToday)){
    				$d = array_shift($arrToday);
    				$arrRes[$d['GoodsID']] = $d;
    			}else if(!empty($arr1)){
    				$d = array_shift($arr1);
    				$arrRes[$d['GoodsID']] = $d;    				
    			}else if(!empty($arr2)){
    				$d = array_shift($arr2);
    				$arrRes[$d['GoodsID']] = $d;     				  				
    			}
    		}else if($rand >= 61 && $rand <= 90){
    			if(!empty($arr1)){
    				$d = array_shift($arr1);
    				$arrRes[$d['GoodsID']] = $d;
    			}else if(!empty($arrToday)){
    				$d = array_shift($arrToday);
    				$arrRes[$d['GoodsID']] = $d;   				
    			}else if(!empty($arr2)){
    				$d = array_shift($arr2);
    				$arrRes[$d['GoodsID']] = $d;      				  				
    			}
    		}else{
    			if(!empty($arr2)){
    				$d = array_shift($arr2);
    				$arrRes[$d['GoodsID']] = $d;
    			}else if(!empty($arr1)){
    				$d = array_shift($arr1);
    				$arrRes[$d['GoodsID']] = $d;    				
    			}else if(!empty($arrToday)){
    				$d = array_shift($arrToday);
    				$arrRes[$d['GoodsID']] = $d;     				  				
    			}
    		}
    	}
    	$arrResult['data'] = $arrRes;
    	return $arrResult;
    }

    public static function getVariedGoodsOnsale($intCatID, $intPage, $intPageSize, $bloIsUpset,$bloIsCache){

    	$key = "GoodsModel_getVariedGoodsOnsale_" . $intCatID;
    	$datas = yii::app()->cache->get($key);
    	if(!($bloIsCache && $datas !== false)){
    		$datas = self::getOnsaleData($intCatID);
    		yii::app()->cache->set($key, $datas, 600);
    	}
    	$arrResult = self::getPageData($datas, $intPage, $intPageSize);
        //打乱顺序
        if($bloIsUpset === true){
            shuffle($arrResult['data']);
        }
        return $arrResult;
    }

    /**
     * 引用,,取数据
     * @return [type] [description]
     */
    public static function getPageData(&$datas,$page,$pagesize){
        //根据你需要的页面获取这一页的数据
        $arrResult['count'] = $datas['count'];
        $arrResult['data'] = array();
        //超过一页
        if($page !== ''){
        	$countPage = ceil($arrResult['count']/$pagesize);//总共几页
			/*        	
			if($countPage < $page){ //如果页码大于总的页数，则直接返回
			        		return $arrResult;
			        	}
			*/
            $objPager = new CPagination($datas['count']);
            $objPager->setCurrentPage($page - 1 < 0 ? 0 : $page - 1);
            $objPager->pageSize = $pagesize;
            $arrResult['page'] = $objPager; 
        	//限定取个数
        	$count = 0;
        	$begin = $objPager->getOffset();
        	foreach ($datas['data'] as $key => $data) {
        		$count++;
        		if($count <= $begin){
        			continue;
        		}else{
        			if($count > ($begin+$pagesize)){
        				break;
        			}
        			$arrResult['data'][$key] = $data;
        		}
        	}            
        }
        return $arrResult;
    }

    public static function getTomorrowList($bloIsCache = true){
    	//获得所有的数据,包括其总数
        $strCache = "GoodsModel_getTomorrowList";

        $datas = yii::app()->cache->get($strCache);
        //如果不是取缓存数据  或者 缓存已经过期
        if(!($bloIsCache && $datas !== false)){
        	$tomorrow = strtotime('tomorrow');
        	$models = self::model()->findAll(BaseModel::getC(array('StartTime' => array('sign' => '>', 'data' => $tomorrow), 'Status' => 1, 'order' => 'Sorting DESC,AddTime DESC')));
        	foreach ($models as $key => $model) {
        		$datas['data'][$model->GoodsID] = $model->attributes;
        	}
        	$datas['count'] = count($datas['data']);
        	yii::app()->cache->set($strCache, $datas, 600);
        }

        return $datas;
    }


    public static function getTomorrow($intPage,$intPageSize,$strOrder, $bloIsCache = true){
    	//获得所有的数据,包括其总数
        $strCache = "GoodsModel_getTomorrow_" . $intPage . '-' . $intPageSize . '' . $strOrder;

        $arrResult = yii::app()->cache->get($strCache);
        //如果不是取缓存数据  或者 缓存已经过期
        if(!($bloIsCache && $arrResult !== false)){
        	$arrResult = array();
        	$tomorrow = strtotime('tomorrow');

	    	$where = " where g.Status = 1 AND g.StartTime >= ".$tomorrow . ' ';

	        $sql_count = "select count(*) from tk_goods g " . $where;

	        $order = self::getOrder($strOrder);

	        




			$connection=Yii::app()->db;
			$command=$connection->createCommand($sql_count);
			$intCount=$command->queryScalar();

	        $arrResult['count'] = $intCount;
	        //如果需要分页则设置分页并取分页对象
	        // && $intCount > $intPageSize
            $objPager = new CPagination($intCount);
            $objPager->setCurrentPage($intPage - 1 < 0 ? 0 : $intPage - 1);
            $objPager->pageSize = $intPageSize;
            $arrResult['page'] = $objPager; 
            $sql = " limit " . $objPager->getOffset() . ' , ' . $intPageSize;


            $sql = "select * from tk_goods g "  . $where . $sql; 

			$command=$connection->createCommand($sql);
			$arrDatas=$command->queryAll();


	        foreach ($arrDatas as $key => $arrData) {
	            $arrResult['data'][$arrData['GoodsID']] = $arrData;
	        }
	        if(empty($arrResult['data'])){
	        	$arrResult['data'] = array();
	        }

        	yii::app()->cache->set($strCache, $arrResult, 600);
        }

        return $arrResult;   	    	
    }


    public static function getOrder($order){
        switch ($order) {
            //销量从大到小
            case 1:
                $order = 'Sales DESC,GoodsID DESC';
                break;
            //价格从小到大
            case 2:
                $order = 'PromoPrice asc,GoodsID DESC';
                break;
            //价格从大到小
            case 3:
                $order = 'PromoPrice DESC,GoodsID DESC';
                break;
            //按人气排名
            case 4:
                $order = 'View DESC,GoodsID DESC';
                break;
/*            case 5:
                $order = 'zonghe';//综合排序，后面实现
                break;*/
            case 6:
                $order = 'Zhekou DESC,GoodsID DESC';//折扣排序
                break;
            case 9:
                $order = 'StartTime DESC,GoodsID DESC';//今日特价排序
                break; 
            case 10:
                $order = 'StartTime desc,Sorting desc';//首页展示的标签商品排序
                break;                                                                                                                 
            default:
                $order = 'Sorting desc, GoodsID desc';//默认排序
                break;  
        }

        return $order;     	
    }


    /**
     * 如果标签是两个以上的组合，则不是以这种方式来获取数据，
     * 如果排序是其它的排序，也不是以这样的方式来获取
     * 根据版块，分类，标签， 专场 来取商品
     * @return [type] [description]
     */
    //                                    1模块ID            2分类ID         3专场ID              4标签列表     5是否首页         6是否免邮             7额外条件    8排序                  9第几页       10每页展示条数       11是否打乱顺序      12是否缓存           13缓存时间
    public static function getVariedGoods($intModuleID = '', $intCatID = '', $intSpecialID = '',  $strTag = '', $intIsIndex = '', $IsFreeShipping = '', $extra = '', $strOrder = 'default', $intPage = 1, $intPageSize = 100,  $bloIsUpset = true, $bloIsCache = true, $intCacheTime = 600){
        $strCache = "GoodsModel_getVariedGoods" . $intModuleID . '_' . $intCatID . '_' . $intSpecialID . '_' . $strTag . '_' . $intIsIndex . '_'  . $IsFreeShipping . '_'   . $extra . '_' . $strOrder . '_' . $intPage . '_' . $intPageSize;

        //如果这些条件的话则是另外的去获取商品

        //$ConditionsExtra = (strpos($strTag, ',') !== false);//标签两个以上
		/*       
 		$arrOrder = array('zonghe');//排序的方式是这种的      
        $ConditionsExtra1 = in_array($strOrder, $arrOrder);
        //如果是这些特殊的条件则使用这样的综合查询
        if(!$extra && ($ConditionsExtra || $ConditionsExtra1)){
        	return self::getVariedGoodsMix($intModuleID, $intCatID, $intSpecialID,  $strTag, $intIsIndex, $IsFreeShipping, $extra, $strOrder, $intPage, $intPageSize,  $bloIsUpset, $bloIsCache, $intCacheTime);
        }
        */


       
        $arrCache = yii::app()->cache->get($strCache);
        //如果不是取缓存数据  或者 缓存已经过期
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }
        



    	$startTime = TIME_TIME + 3600;


        if($strTag !== ''  && $intModuleID !== ''){
        	if(is_numeric($strTag)){
        		$TagID = " TagID = {$strTag} ";
        	}else{
        		$TagID = " TagID in({$strTag}) ";
        	}
            $sql = "select * from tk_goods_module_tag  where {$TagID}  AND ModuleID = {$intModuleID} and StartTime <= ".$startTime." AND EndTime > ".TIME_TIME;  
        }else if($strTag !== ''){
        	if(is_numeric($strTag)){
        		$TagID = " TagID = {$strTag} ";
        	}else{
        		$TagID = " TagID in({$strTag}) ";
        	}        	
        	$sql = "select * from tk_goods_tag  where {$TagID} and StartTime <= ".$startTime." AND EndTime > ".TIME_TIME; 
        }else if($intModuleID !== ''){
        	$sql = "select * from tk_goods_module  where ModuleID = {$intModuleID} and StartTime <= ".$startTime." AND EndTime > ".TIME_TIME;    
        }else{
        	$sql = "select * from tk_goods g where g.Status = 1 and g.StartTime <= ".$startTime." AND g.EndTime > ".TIME_TIME;   
        }





        //分类的条件
        if($intCatID !== ''){
            $intCatID = CategoryModel::getStrChildid($intCatID);
            if(is_numeric($intCatID)){
                $sql .= " AND CatID = {$intCatID}";  
            }else{
                $sql .= " AND CatID in({$intCatID})";  
            }            
        }

        //专场的条件
        if($intSpecialID !== ''){
        	$sql .= " AND SpecialID = {$intSpecialID}";     
        }




        //是否首页展示的条件
        if($intIsIndex !== ''){
        	$sql .= " AND IsIndex = {$intIsIndex}";   
        }   

        //是否免邮
        if($IsFreeShipping !== ''){
        	$sql .= " AND IsFreeShipping = {$IsFreeShipping}";   
        }       	

        //额外的条件
        switch ($extra) {
        	case 1:
        		$sql .= ' and PromoPrice <= 9.9 and IsFreeShipping = 1';
        		break;
        	case 2:
        		$sql .= ' and PromoPrice <= 19.9 ';
        		break;
        }

        //排序
        $order = '';
        $strOrder = self::getOrder($strOrder);
        $order = " order by  {$strOrder}";;
        	
        //echo $sql;exit;
        $sql_count = str_replace('*', 'count(*)', $sql);

        $sql = $sql .  $order;
        $arrResult = array();
		/*       
	    $connection=Yii::app()->db;
        $command=$connection->createCommand($sql_count);
        $rows=$command->queryAll();      // 查询并返回结果中的所有行
        $row=$command->queryRow();       // 查询并返回结果中的第一行
        $column=$command->queryColumn(); // 查询并返回结果中的第一列
		$value=$command->queryScalar();  // 查询并返回结果中第一行的第一个字段
		*/
	
		$connection=Yii::app()->db;	
		if($intPage === ''){
			$arrResult['count'] = $intPageSize;
	        if($intPageSize !== ''){
	        	//限定取个数
	        	$sql .= " limit {$intPageSize}";
	        }			
		}else{
			$command=$connection->createCommand($sql_count);
			$intCount=$command->queryScalar();

	        $arrResult['count'] = $intCount;

            $objPager = new CPagination($intCount);
            $objPager->setCurrentPage($intPage - 1 < 0 ? 0 : $intPage - 1);
            $objPager->pageSize = $intPageSize;
            $arrResult['page'] = $objPager; 
            $sql .= " limit " . $objPager->getOffset() . ' , ' . $intPageSize; 
		}


		$command=$connection->createCommand($sql);
		$arrDatas=$command->queryAll();


        foreach ($arrDatas as $key => $arrData) {
            $arrResult['data'][$arrData['GoodsID']] = $arrData;
        }
        if(empty($arrResult['data'])){
        	$arrResult['data'] = array();
        }


        //打乱顺序
        if($bloIsUpset === true){
            shuffle($arrResult['data']);
        }

        yii::app()->cache->set($strCache, $arrResult, $intCacheTime);
        return $arrResult;
    }



    public static function getDataIndexAjax($ModuleID, $TagID){
		return $data = self::getVariedGoods($ModuleID, '', '', $TagID, '','','',  10, '', 8, false, true, 600);
    }

    //获取首页的标签，模块六层这组合
    public static function getIndexMTMix($bloIsCache = true){
        $strCache = "GoodsModel_getIndexMTMix";
        $arrCache = yii::app()->cache->get($strCache);
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }


    	//先获取首页需要显示的模块
    	$arrDatas = ModuleModel::getIndexList();
    	$arrResult = array();
    	//然后获取各个模块下有哪些分类
    	$arrTags = TagModel::getList();    	
    	foreach ($arrDatas as $ModuleID => $arrData) {
    		//需要展示的分类列表
    		$arrTagIDs = explode(',', $arrData['TagIDs']);
    		$arrResult[$ModuleID] = $arrData;
    		//$count = 0;
    		foreach ($arrTagIDs as $TagID) {
    			//$count++;
    			$arrResult[$ModuleID]['data'][$TagID] = $arrTags[$TagID];
    			$arrResult[$ModuleID]['category'][$TagID] = $arrResult[$ModuleID]['data'][$TagID]['Title'];
    			//if($count == 1){
    				//$arrResult[$ModuleID]['data'][$TagID]['data'] = self::getVariedGoods($ModuleID, '', '', $TagID, '','','',  10, '', 8, false, true, 600);
    			//}
    		}
    	}
    	
    	yii::app()->cache->set($strCache, $arrResult, 3600);
    	return $arrResult;
    }



    /**
     * 组合首页需要显示的数据
     * 模块 下面 data是各分类  ,各分类下面的data是各商品
     * @return [type] [description]
     */
    public static function getDataIndex(){
    	$datas = self::getIndexMTMix();
/*    	$ModuleID = key($datas);
    	$TagID = key($datas[$ModuleID]['category']);
    	$datas[$ModuleID]['data'][$TagID]['data'] = self::getVariedGoods($ModuleID, '', '', $TagID, '','','',  10, '', 8, false, true, 600);
    	return $datas;*/
    	foreach($datas as $ModuleID => $arrData){
    		$TagID = key($arrData['category']);
    		$datas[$ModuleID]['data'][$TagID]['data'] = self::getVariedGoods($ModuleID, '', '', $TagID, '','','',  10, '', 8, false, true, 600);
    	}
    	return $datas;
    }




    /**
     * 组合首页需要显示的数据
     * 模块 下面 data是各分类  ,各分类下面的data是各商品
     * @return [type] [description]
     */
    public static function getDataIndex_bak(){
    	//先获取首页需要显示的模块
    	$arrDatas = ModuleModel::getIndexList();
    	$arrResult = array();
    	//然后获取各个模块下有哪些分类
    	$arrTags = TagModel::getList();    	
    	foreach ($arrDatas as $ModuleID => $arrData) {
    		//需要展示的分类列表
    		$arrTagIDs = explode(',', $arrData['TagIDs']);
    		$arrResult[$ModuleID] = $arrData;
    		$count = 0;
    		foreach ($arrTagIDs as $TagID) {
    			$count++;
    			$arrResult[$ModuleID]['data'][$TagID] = $arrTags[$TagID];
    			$arrResult[$ModuleID]['category'][$TagID] = $arrResult[$ModuleID]['data'][$TagID]['Title'];
    			if($count == 1){
    				$arrResult[$ModuleID]['data'][$TagID]['data'] = self::getVariedGoods($ModuleID, '', '', $TagID, '','','',  10, '', 8, false, true, 600);
    			}
    		}
    	}
    	return $arrResult;
    }

    //获取所有的有选的键值
    public function getTag(){
    	$arr = TagGoodsModel::getListField($this->GoodsID, 'TagID');
    	return $arr;
    }


    //获取所有的有选的键值
    public function getModule(){
    	$arr = ModuleGoodsModel::getListField($this->GoodsID, 'ModuleID');
    	return $arr;
    }

	/**
	 * 状态
	 * @return [type] [description]
	 */
	public static function getStatusHtml($mixData = false){
		$arrData = array(
			1 => '上架',	
			5 => '下架',						
		);
		if($mixData !== false){
			return $arrData[$mixData];
		}else{
			return $arrData;
		}
	}

	public static function getOne($goodsID, $bloIsCache = true){
		if(!is_numeric($goodsID)){
			return array();
		}
		$strKey = "GoodsModel_getOne" . $goodsID;
		$arrCache = yii::app()->cache->get($strKey);
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrCache = array();

        $arrCache = self::model()->findByPk($goodsID);
        $arrCache = empty($arrCache) ? array() : $arrCache->attributes;

        yii::app()->cache->set($strKey, $arrCache, 1800);
        return $arrCache;	

	}

	/**
	 * 获取所有的正在上架的商品
	 * @return [type] [description]
	 */
	public static function getList($bloIsCache = true){
		$strKey = "GoodsModel_getList";
		$arrCache = yii::app()->cache->get($strKey);
        if($bloIsCache && $arrCache !== false){
            return $arrCache;
        }

        $arrCache = array();
        $objModels = self::model()->findAll(array('condition' => "Status = 1 AND StartTime <= " . TIME_TIME . " AND EndTime > " . TIME_TIME, 'order' => 'Sorting DESC, GoodsID DESC' ));
        foreach ($objModels as $key => $objModel) {
        	$arrCache[$objModel->GoodsID] = $objModel->attributes;
        }
        yii::app()->cache->set($strKey, $arrCache, 600);
        return $arrCache;	
	}

}
